<?php

class Backend_ShoppingController extends RCMS_Core_BaseController {

	protected $_configTableArray;

	protected $_smtpConfigArray;

	protected $_domain;

	protected $_smtpHost;

	protected $_smtpLogin;

	protected $_smtpPassword;

	protected $_adminShoppingEmail;

	/**
	 * Init function.
	 * @return <void>
	 */
	public function init()
    {
        parent::init();
        $params = $this->getRequest()->getParams();
        $allowActions = array('addtocart', 'recount', 'viewsc', 'quoteme', 'handlerpaypalaccount', 'handlerpaypalcreditcard');
        if (!in_array($params['action'], $allowActions)) {
            parent::checkLogin();
        }
		$this->_model = new Default_Model_ShoppingModel();
		$this->_initSmtp();
	}

	/**
	 * This function loads template where user can add and edit a product.
	 * @return <void>
	 */
	public function productAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
        $this->view->productId = intval($this->getRequest()->getParam('id'));
		$this->view->listFolders = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images);
		$this->view->groups = $this->_model->selectGroups();
		$this->view->products = $this->_model->selectAllProducts();

		//for translator
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}

	/**
	 * This function loads template where user can change config for shopping.
	 * @return <void>
	 */
	public function configAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
        $this->view->update = false;
        
        if ($this->getRequest()->isPost() && $this->getRequest()->getParam('submit') === 'Save') {
           /* save settings for shopping config */
            $settingsPayPal = array(
                'email'       =>  trim($this->getRequest()->getParam('paypalemail')),
                'signature'   =>  trim($this->getRequest()->getParam('paypalsignature')),
                'user'        =>  trim($this->getRequest()->getParam('paypaluser')),
                'password'    =>  trim($this->getRequest()->getParam('paypalpassword'))
            );
            $data = array (
                'company'               =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('company'))),
                'address'               =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('address'))),
                'phone'                 =>  trim($this->getRequest()->getParam('phone')),
                'email'                 =>  trim($this->getRequest()->getParam('email')),
                'currency'              =>  trim($this->getRequest()->getParam('currency')),
                'tax'                   =>  trim($this->getRequest()->getParam('tax')),
                'gateway'               =>  trim($this->getRequest()->getParam('gateway')),
                'quote'                 =>  (strtolower($this->getRequest()->getParam('quote')) == 'true' ? '1' : '0'),
                'template_product'      =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('template-product'))),
                'template_prod_list'    =>  trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('template-prod-list'))),
                'paypal'                =>  serialize($settingsPayPal),
                'company_logo'          =>  trim($this->getRequest()->getParam('company-logo'))
            );
            foreach ($data as $key => $value) {
                $this->_model->updateShoppingConfig($key, $value);
            }
            /* save logo of company for shopping config */
            /*$path = $this->_config->website->website->path . 'public/system/images/shoppinglogo/';
            if (!is_dir($path)) {
                @mkdir($path, 755);
            }
            if (is_dir($path) && is_writable($path)) {
            $logo = new Zend_File_Transfer_Adapter_Http();
                if ($logo->isUploaded()) {
                    $data = $logo->getFileInfo();
                    $logo->addValidator('Extension', false, 'jpg,png,gif');
                    preg_match('/\.(.+)$/', $logo->getFileName(null, false), $tmp);
                    $logo->addFilter('Rename', array('source' => $data['Filedata']['tmp_name'], 'target' => $path.'logo.'.$tmp[1], 'overwrite' => true));
                    if ($logo->isValid()) {
                        $files = @scandir($path);
                        foreach ($files as $file) {
                            if($file == '.' || $file == '..') {
                                continue;
                            }
                            if (is_file($path.$file)) {
                                @unlink($path.$file);
                            }
                        }
                        $logo->setDestination($path);
                        $saveLogo = $logo->receive();
                        if ($saveLogo) {
                            $this->_model->updateShoppingConfig('company_logo', 'logo.'.$tmp[1]);
                        }
                    }
                }
            }*/
            $this->view->update = true;
        }
        /* load settings */
        $this->view->listFolders = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images);
		$this->view->shoppingConfig = $this->_model->selectShoppingConfig();
        $this->view->logoCompany = '';
        if (file_exists($this->_config->website->website->path.'public/'.$this->view->shoppingConfig['company_logo']) &&
                is_file($this->_config->website->website->path.'public/'.$this->view->shoppingConfig['company_logo'])) {
            $this->view->logoCompany = $this->view->websiteUrl.$this->view->shoppingConfig['company_logo'];
        }

		//for translator
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}

	/**
	 * This function loads images for selected folder. (AJAX)
	 * @return <string> (json)
	 */
	public function loadimagesAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		if ($this->getRequest()->isPost()) {
			$folder = trim($this->getRequest()->getParam('folder'));
			if ($folder === '') { return; }
			$smallImages = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images . $folder . '/small/');
			$path = $this->_config->website->website->url . 'images/' . $folder . '/';
			$contentSmallImages = '<div style="border-bottom:1px solid #7c7c7c;margin-bottom:3px;height:20px;text-align:right;" onclick="this.parentNode.style.display=\'none\';"><span style="cursor:pointer;color:#7c7c7c;font-weight:bold;"> Close </span></div>';
			if (count($smallImages) > 0) {
				foreach ($smallImages as $image) {
					$contentSmallImages .= '<img title="' . $image . '"  onclick="shop.selectImage(\'' . $path . 'small/' . $image . '\');" style="vertical-align:top; margin: 0px 0px 1px 1px;cursor:pointer;" border="0" width="55" src="' . $path . 'small/' . $image .'">';
				}
				$contentSmallImages .= '<div style="clear:both;height:0px;">&nbsp;</div>';
			}
			echo json_encode(array('small' => $contentSmallImages)); return;
		}
	}

	/**
	 * This function adds new group. (AJAX)
	 * @return <string> (json)
	 */
	public function addgroupAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		if ($this->getRequest()->isPost()) {
			$group = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('group', '')));
			if ($group === '') {
				echo json_encode(array('exist' => false, 'save' => false)); return;
			}
			$ifExist = $this->_model->selectGroupByName($group);
			if (!empty($ifExist)) {
				echo json_encode(array('exist' => true, 'save' => false)); return;
			}
			$result = (integer) $this->_model->insertGroup($group);
			if ($result > 0) {
				echo json_encode(array('exist' => false,'save' => true, 'id' => $result)); return;
			}
		}
	}

	/**
	 * This function deletes a group. (AJAX)
	 * @return <string> (json)
	 */
	public function deletegroupAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		if ($this->getRequest()->isPost()) {
			$id = (integer) $this->getRequest()->getParam('id', 0);
			if ($id === 0) {
				echo json_encode(array('del' => false)); return;
			}
			$result = $this->_model->deleteGroup($id);
			if ($result > 0) {
				echo json_encode(array('del' => true)); return;
			}
		}
	}

	/**
	 * This function returns data about products for shopping. (AJAX)
	 * @return <string>
	 */
	public function productsforautocompleteAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		if ($this->getRequest()->isPost()) {
			$products = $this->_model->selectAllProducts();
			$dataProducts = '';
			if (is_array($products) && count($products) > 0) {
				foreach ($products as $product) {
					$dataProducts .= $product['name'] . ':::' . $product['photo'] . ':::' . $product['id'] . ':::' . $product['item_id'] . '###';
				}
			}
			echo $dataProducts; return;
		}
	}

	/**
	 * This function adds new product. (AJAX)
	 * @return <string> (json)
	 */
	public function addproductAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
        
		if ($this->getRequest()->isPost()) {
            /* got variables */
			$name = trim($this->getRequest()->getParam('name'));
			$itemId = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('item_id')));
			$price = $this->getRequest()->getParam('price');
			$photo = trim($this->getRequest()->getParam('photo'));
			$brand = strtoupper(trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('brand'))));
			$desc = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('desc')));
			$options = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('options')));
			$related = rtrim($this->getRequest()->getParam('related'), ',');
			$groups = explode(',', rtrim($this->getRequest()->getParam('groups'), ','));
            /* create new product */
			$product = new RCMS_Object_Product_Product();
			$product->setName($name);
			$product->setItemId($itemId);
			$product->setPrice($price);
			$product->setPhoto($photo);
			$product->setBrand($brand);
			$product->setDescription($desc);
			$product->setOptions($options);
			$product->setRelated($related);
			$idProduct = $product->save();
            
			if ($idProduct > 0) {
				$product->setId($idProduct);
				if(isset($groups[0]) && $groups[0]) {
					$product->setGroups($groups);
				}
                /* save page */
				$ifSave = $this->_savePageForProduct($product);
				$pageUrl = $ifSave === true ? preg_replace('/([@!.:;\'"`$%?&()*|\s\/\\\])/', '-', $product->getName().'-'.$product->getItemId()) : '';
				echo json_encode(array('id' => $idProduct, 'url' => $pageUrl)); return;
			}
			echo json_encode(array('id' => 0)); return;
		}
	}

	/**
	 * This function creates and saves a page for a product.
	 * @param <object> $product
	 * @return <boolean>
	 */
	private function _savePageForProduct($product)
    {
		if ($product instanceof RCMS_Object_Product_Product) {
			$templateForProduct = $this->_model->selectTemplateByName('product');
			if (!$templateForProduct) {
				$templateForProduct = $this->_model->selectTemplateByName('default');
			}
			$idCategoryProduct = $this->_model->selectCategoryProducts();
			if (!$idCategoryProduct) {
				$idCategoryProduct = $this->_model->insertCategoryProducts(0, RCMS_Object_QuickConfig_QuickConfig::$productsCategoryName);
				$pageCategory = new RCMS_Object_Page_Page();
				$pageCategory->setH1Tag(RCMS_Object_QuickConfig_QuickConfig::$productsCategoryName);
				$pageCategory->setHeaderTitle(RCMS_Object_QuickConfig_QuickConfig::$productsCategoryName);
				$pageCategory->setUrl(RCMS_Object_QuickConfig_QuickConfig::$productsCategoryUrl);
				$pageCategory->setNavName(RCMS_Object_QuickConfig_QuickConfig::$productsCategoryName);
				$pageCategory->setMetaDescription('');
				$pageCategory->setShortDescription('');
				$pageCategory->setCategoryId($idCategoryProduct);
				$pageCategory->setTemplateId($templateForProduct);
				$pageCategory->setFeaturedId(0);
				$pageCategory->setIs404Page(0);
				$pageCategory->setOrder(100);
				$ownerId = unserialize($this->_session->currentUser)->getId() > 0 ? unserialize($this->_session->currentUser)->getId() : 0;
				$pageCategory->setOwner($ownerId);
				$pageCategory->setSeosambaRuleId(0);
				$pageCategory->setShowInMenu(1);
				$pageCategory->setSiloId(0);
				$pageCategory->setStaticOrder(100);
				$pageCategory->setBestPractices(0);
				$pageCategory->setLastUpdate(date("Y-m-d H:i:s"));
				$pageCategory->setWeight(0);
				$pageCategory->setTargetedKeyPhrase(RCMS_Object_QuickConfig_QuickConfig::$productsCategoryName);
				$pageCategory->save();
				unset ($pageCategory);
			}
			$pageUrl = preg_replace('/([@!.:;\'"`$%?&()*|\s\/\\\])/', '-', $product->getName().'-'.$product->getItemId());
			$idCategoryForPage = $this->_model->insertCategoryProducts($idCategoryProduct, $pageUrl);
			$page = new RCMS_Object_Page_Page();
			$page->setH1Tag($pageUrl);
			$page->setHeaderTitle($pageUrl);
			$page->setUrl($pageUrl);
			$page->setNavName($pageUrl);
			$page->setMetaDescription($product->getDescription());
			$page->setShortDescription($product->getDescription());
			$page->setCategoryId($idCategoryForPage);
			$page->setTemplateId($templateForProduct);
			$page->setFeaturedId(0);
			$page->setLastUpdate(date("Y-m-d H:i:s", time()));
			$page->setIs404Page(0);
			$page->setOrder(100);
			$ownerId = unserialize($this->_session->currentUser)->getId() > 0 ? unserialize($this->_session->currentUser)->getId() : 0;
			$page->setOwner($ownerId);
			$page->setSeosambaRuleId(0);
			$page->setShowInMenu(1);
			$page->setSiloId(0);
			$page->setStaticOrder(100);
			$page->setBestPractices(0);
			$page->setWeight(0);
			$page->setTargetedKeyPhrase($pageUrl);
			$save = $page->save();
			if ($save !== false) {
				$product->setPageId($save);
				$product->save();
                $template = new RCMS_Object_Template_Template($templateForProduct);
                preg_match('/content:(.*)}/', $template->getContent(), $matches);
                if (isset($matches[1])) {
                    $this->_saveConatainer($matches[1], $save);
                }               
                unset ($template);
				unset ($page);
				return true;
			}
			return false;
		}
		return false;
	}

    private function _saveConatainer($name, $pageId)
    {
        $name = trim($name);
        $pageId = intval($pageId);
        if ($name == '' || $pageId <= 0) {
            return false;
        }
        $container = new RCMS_Object_Container_Container();
        $container->setType(1);
        $container->setUserId(unserialize($this->_session->currentUser)->getId());
        $container->setPageId($pageId);
        $container->setName($name);
        $container->setPublished(true);
        $container->setIsForSale(true);
        $container->setAllowComments(true);
        $container->setPublishingDate(date('Y-n-d G-i-s'));
        $container->setContent('{$product}');
        $save = $container->save();
        unset ($container);
        if ($save !== false) {
            return true;
        }
        return false;
    }

	/**
	 * This function returns data about a product. (AJAX)
	 * @return <string> (json)
	 */
	public function getdataproductAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		if ($this->getRequest()->isPost()) {
			$id = intval($this->getRequest()->getParam('id'));
			$product = new RCMS_Object_Product_Product($id);
			if ($product->getId() > 0) {
				$gr = $product->getGroups();
				$groups = '';
				foreach ($gr as $g) {
					$groups .= $g['id'].',';
				}
                $groups = rtrim($groups, ',');
				$page = new RCMS_Object_Page_Page($product->getPageId());
				$data = array(
					'id'        => $product->getId(),
					'name'      => $product->getName(),
					'item_id'   => $product->getItemId(),
					'brand'     => $product->getBrand(),
					'price'     => $product->getPrice(),
					'photo'     => $product->getPhoto(),
					'desc'      => $product->getDescription(),
					'options'   => $product->getOptions(),
					'related'   => $product->getRelated(),
					'groups'    => $groups,
					'pageurl'   => $page->getUrl()
				);
				echo json_encode($data); return;
			}
			echo json_encode(array('id' => 0)); return;
		}
	}

	/**
	 * This function deletes a product. (AJAX)
	 * @return <string> (json)
	 */
	public function deleteproductAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		if ($this->getRequest()->isPost()) {
			$id = (integer) $this->getRequest()->getParam('id');
			$product = new RCMS_Object_Product_Product($id);
			if ($product->getId() <= 0) {
				echo json_encode(array('del' => false)); return;
			}
			$flagDelete = $product->delete();
			if ($flagDelete) {
				$page = new RCMS_Object_Page_Page($product->getPageId());
				$page->delete();
				echo json_encode(array('del' => true)); return;
			}
			echo json_encode(array('del' => false)); return;
		}
	}

	/**
	 * This function edits a product. (AJAX)
	 * @return <string> (json)
	 */
	public function editproductAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		if ($this->getRequest()->isPost()) {
			$id = (integer) $this->getRequest()->getParam('id');
			$name = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('name')));
			$itemId = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('item_id')));
			$price = $this->getRequest()->getParam('price');
			$photo = trim($this->getRequest()->getParam('photo'));
			$brand = strtoupper(trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('brand'))));
			$desc = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('desc')));
			$options = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('options')));
			$related = rtrim($this->getRequest()->getParam('related'), ',');
			$groups = explode(',', rtrim($this->getRequest()->getParam('groups'), ','));
			$product = new RCMS_Object_Product_Product($id);
			if ($product->getId() <= 0) {
				echo json_encode(array('save' => false)); return;
			}
			$product->setName($name);
			$product->setItemId($itemId);
			$product->setPrice($price);
			$product->setPhoto($photo);
			$product->setBrand($brand);
			$product->setDescription($desc);
			$product->setOptions($options);
			$product->setRelated($related);
			$save = $product->save();
			if ($save !== false) {
				$product->setGroups($groups);
				echo json_encode(array('save' => true)); return;
			}
			echo json_encode(array('save' => false)); return;
		}
	}

    public function getbrandsAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		if ($this->getRequest()->isPost()) {
			$brands = $this->_model->selectBrands();
			$out = '';
			if (is_array($brands) && count($brands) > 0) {
				foreach ($brands as $brand) {
					$out .= $brand['brand'].'###';
				}
			}
			echo $out; return;
		}
	}


	public function editgroupAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		if ($this->getRequest()->isPost()) {
			$id = (integer) $this->getRequest()->getParam('id');
			$name = trim(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('name')));
			if ($name === '' || $id <= 0) {
				echo json_encode(array('save' => false)); return;
			}
			$save = $this->_model->updateGroup($name, $id);
			if ($save !== false) {
				echo json_encode(array('save' => true)); return;
			}
			echo json_encode(array('save' => false)); return;
		}
	}

	public function addtocartAction()
    {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		if ($this->getRequest()->isPost()) {
			$id = intval($this->getRequest()->getParam('id'));
			$options = $this->getRequest()->getParam('opts');
			if($options) {
				$itemOptions = array();
				$explodedOpt = explode(',', $options);
				if(sizeof($explodedOpt) > 0) {
					foreach ($explodedOpt as $optionData) {
						$explodedOptData = explode('=', $optionData);
						if(sizeof($explodedOptData) > 0) {
							$itemOptions[$explodedOptData[0]] = $explodedOptData[1];
						}
					}
				}
			}
			$shoppingCart = new RCMS_Object_Shopping_ShoppingCart();
			$shoppingCart->addItem(array(
				'id' => $id,
				'options' => is_array($itemOptions) ? $itemOptions : array()
			));
			echo json_encode(array('itemsCount' => $shoppingCart->getItemsCountForCart(), 'totalPrice' => $shoppingCart->getTotalPrice()));
		}
	}

	public function viewscAction()
    {
        $this->_helper->viewRenderer->setNoRender(true);
		$shoppingConfigData = $this->_model->selectShoppingConfig();
		$shoppingCart = new RCMS_Object_Shopping_ShoppingCart();
		$this->view->products = $shoppingCart->getProductsList();
		$this->view->total = $shoppingCart->getTotalPrice();
        $config = $this->_model->selectShoppingConfig();
        $this->view->currency = isset($config['currency']) && strlen($config['currency']) == 3 ? $config['currency'] : '';
        $this->view->config = $config;
        $this->view->settingsPayPal = unserialize($config['paypal']);
		$this->view->logoPath = $this->getWebSiteUrl();
		$this->view->companyLogoName = $shoppingConfigData['company_logo'];
		$this->view->companyName = $shoppingConfigData['company'];
		$this->view->companyEmail = $shoppingConfigData['email'];
		$this->view->companyPhone = $shoppingConfigData['phone'];
		$this->view->companyAddress = $shoppingConfigData['address'];
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		echo $content;
	}

	public function recountAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$toRemove   = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('toremove')));
		$toRecount  = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('torecount')));
		$options    = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('options')));
		$remOptions = json_decode(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('remOptions')));
		$shoppingCart = new RCMS_Object_Shopping_ShoppingCart();
		if(!empty($toRemove)) {
			$remOptions = $this->_makeOptions($remOptions);
			foreach ($toRemove as $key => $removeItem) {
				$optKey = str_replace('todelete-', '', $removeItem);
				$removeItem = preg_replace('/todelete-([0-9]+)-[0-9]+/', '$1', $removeItem);
				$shoppingCart->removeItem($removeItem, $remOptions[$optKey]);
			}
		}
		//var_dump($toRecount); die();
		if(!empty ($toRecount)) {
			$options = $this->_makeOptions($options);
			foreach ($toRecount as $key => $recountItem) {
				//var_dump($options); die();
				$recountItemData = explode(',', $recountItem);
				$recountItemId = preg_replace('/itmcount-([0-9]+)-[0-9]+/', '$1', $recountItemData[0]);
				$desiredNumber = $recountItemData[1];
				$howManyToAdd = $desiredNumber - $shoppingCart->getItemsCount($recountItemId, $options[$recountItemId . '-' . $key]);
				var_dump($howManyToAdd);
				if($howManyToAdd > 0) {
					$shoppingCart->increaseItemNumber($recountItemId, $howManyToAdd, $options[$recountItemId . '-' . $key]);
				}
				else {
					$shoppingCart->decreaseItemNumber($recountItemId, abs($howManyToAdd), $options[$recountItemId . '-' . $key]);
				}
				if($desiredNumber == 0) {
					$shoppingCart->removeItem($recountItemId, $options[$recountItemId . '-' . $key]);
				}
			}
		}
	}

	private function _makeOptions($options) {
		$rightOpts = array();
		foreach ($options as $optString) {
			$explodedOptString = explode(',', $optString);
			$explodedOptVals = explode('=', $explodedOptString[1]);
			$rightOpts[$explodedOptString[0]][$explodedOptVals[0]] = $explodedOptVals[1];
		}
		return $rightOpts;
	}

	private function _generateEmailBodyForAdmin($formData) {
		$userName = $formData['name'];
		$userEmail = $formData['email'];
		$userAddressOne = (isset($formData['address1']))? trim($formData['address1']) : "Not Set";
		$userAddressTwo = (isset($formData['address2']))? trim($formData['address2']) : "Not Set";
		$city = (isset($formData['city']))? trim($formData['city']) : "Not Set";
		$state = (isset($formData['state']))? trim($formData['state']) : "Not Set";
		$zip = (isset($formData['zip']))? trim($formData['zip']) : "Not Set";
		$country = (isset($formData['country']))? trim($formData['country']) : "Not Set";
		$phone = (isset($formData['phone']))? trim($formData['phone']) : "Not Set";
		$comments = (isset($formData['comments']))? trim($formData['comments']) : "Not Set";

		if($userName && $userEmail) {
			$userName = ucfirst(strtolower(trim($userName)));
			$userEmail = trim($userEmail);
			$userAddress = trim($userAddress);

			$text = "Hello,";
			$text .= "\nUser ".$userName.", who has an email ".$userEmail;
			$text .= " sent a request for a shopping quote.";
			$text .= "\nUser information: ";
			$text .= "\n First Address: ".$userAddressOne;
			$text .= "\n Second Address: ".$userAddressTwo;
			$text .= "\n Country: ".$country;
			$text .= "\n State: ".$state;
			$text .= "\n City: ".$city;
			$text .= "\n Zip: ".$zip;
			$text .= "\n Phone: ".$phone;
			$text .= "\n Comments: ".$comments;
			$text .= "\n\nPlease login to the system to process this request.";
			return $text;
		}
		return '';
	}

	private function _generateEmailBodyForUser($userName) {
		if($userName) {
			$userName = ucfirst(strtolower(trim($userName)));
			return "Hello, " . $userName . "!\nYou have requested a quote from ".$this->getWebSiteUrl().$this->_pageUrl." cart system.\nOur administrators will contact you as soon as possible.\nThank you!";
		}
		return '';
	}

	public function sendEmail($to, $toComment, $from, $fromComment, $subject, $body, $useSmtp) {
		if ($useSmtp) {
			$tr = new Zend_Mail_Transport_Smtp($this->_smtpHost, $this->_smtpConfigArray);
			Zend_Mail::setDefaultTransport($tr);
			$mailer = new Zend_Mail( 'utf-8' );
			$mailer->addTo($to,$toComment);
			$mailer->setFrom($from, $fromComment);
			$mailer->setSubject($subject);
			$mailer->setBodyText($body);
			try {
				$mailer->send();
				return true;
			} catch (Exception $e) {
				return false;
			}
		} else {
			$mailer = new Zend_Mail( 'utf-8' );
			$mailer->addTo($to,$toComment);
			$mailer->setFrom($from, $fromComment);
			$mailer->setSubject($subject);
			$mailer->setBodyText($body);
			try {
				$mailer->send();
				return true;
			} catch (Exception $e) {
				return false;
			}
		}
	}

	private function _checkSmtpAllowedInConfig() {
		if(isset($this->_configTableArray['use_smtp']) && $this->_configTableArray['use_smtp'] == 1 &&
			isset($this->_configTableArray['smtp_login']) && $this->_configTableArray['smtp_login'] != '' &&
			isset($this->_configTableArray['smtp_password']) && $this->_configTableArray['smtp_password'] != '') {
			return true;
		}
		return false;
	}

	private function _initSmtp() {
		$this->_domain = ($this->_smtpHost)? ucfirst($this->_smtpHost) : $this->_websiteUrl;
		$configArray = $this->_model->selectAllConfigSettings();
		if($configArray) {
			$this->_configTableArray = $configArray;
			if(isset($configArray['smtp_host']) && $configArray['smtp_host'] != '') {
				$this->_smtpHost = $configArray['smtp_host'];
			}
			if(isset($configArray['smtp_login']) && $configArray['smtp_login'] != '') {
				$this->_smtpLogin = $configArray['smtp_login'];
			}
			if(isset($configArray['smtp_password']) && $configArray['smtp_password'] != '') {
				$this->_smtpPassword = $configArray['smtp_password'];
			}

			$this->_smtpConfigArray = array(
				'auth'      => 'login',
				'username'  => $this->_smtpLogin,
				'password'  => $this->_smtpPassword,
				'host'      => $this->_smtpHost
			);
		}
	}

    public function quotemeAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
        
        if ($this->getRequest()->isPost()) {
            $formData =  $this->getRequest()->getParams();
            $userName = $formData['name'];
            $userEmail = $formData['email'];
            /* get smtp settings */
            $configArray = $this->_model->selectAllConfigSettings();
            $useSmtpInConfig = $this->_checkSmtpAllowedInConfig();
            
            if ($useSmtpInConfig) {
                $useSmtp = true;
            } else {
                $useSmtp = false;
            }
            $shoppingCardAdminEmail = $this->_model->selectShoppingCartAdminEmail();
            /* send email to admin from shopping table */
            $to = $shoppingCardAdminEmail;
            $from = $this->_configTableArray['admin_email'];
            $toComment = '';
            $fromComment ='';
            $subject = 'A new qoute request on '.$this->getWebSiteUrl();
            $body = $this->_generateEmailBodyForAdmin($formData);
            $flag = $this->sendEmail($shoppingCardAdminEmail, $toComment, $from, $fromComment, $subject, $body, $useSmtp);
            /* send email to client */
            $to = $userEmail;
            $from = $shoppingCardAdminEmail;
            $toComment = '';
            $fromComment ='';
            $subject = 'Qoute request registred on '.$this->getWebSiteUrl();
            $body = $this->_generateEmailBodyForUser($userName);
            $flag = $this->sendEmail($to, $toComment, $from, $fromComment, $subject, $body, $useSmtp);
            /*saving cart and put a new quote */
            if ($flag) {
                /* load session based cart */
                $shoppingCart = new RCMS_Object_Shopping_ShoppingCart();
                /* create and save cart for current user */
                $userCart = new RCMS_Object_Shopping_ShoppingUserCart();
                $userCart->setName($userName);
                $userCart->setEmail($userEmail);
                $userCart->setAddress1($formData['address1']);
                $userCart->setAddress2($formData['address2']);
                $userCart->setCity($formData['city']);
                $userCart->setCountry($formData['country']);
                $userCart->setState($formData['state']);
                $userCart->setZip($formData['zip']);
                $userCart->setPhone($formData['phone']);
                $userCart->setComments(strip_tags($formData['comments']));
                $userCart->setCartData($shoppingCart->getProductsList());
                $newCartId = $userCart->save();
                /* creating new quote */
                $quote = new RCMS_Object_Quote_Quote();
                $quote->setShoppingCartId($newCartId);
                $quote->setName($userName);
                $quote->setStatus(RCMS_Object_Quote_Quote::Q_STATUS_NEW);
                $quote->save();
                echo json_encode(array('done' => true)); return;
            }
            echo json_encode(array('done' => false)); return;
		}
    }

    public function handlerpaypalaccountAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

        if ($this->getRequest()->isPost()) {
            $data =  $this->getRequest()->getParams();
            
            if ($data['payment_type'] == 'instant') {
                unset ($data['controller']);
                unset ($data['action']);
                unset ($data['module']);
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, 'https://www.paypal.com/cgi-bin/webscr');
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_VERBOSE, 1);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array_merge(array('cmd'=>'_notify-validate'), $data)));
                $response = curl_exec($ch);
                curl_close($ch);

                if ($response == 'VERIFIED') {
                    $dataPayment = array(
                        'transaction_id'    =>  $data['txn_id'],
                        'amount'            =>  $data['mc_gross'],
                        'payer_id'          =>  $data['payer_id'],
                        'description'       =>  $data['item_name'],
                        'billing_name'      =>  $data['address_name'],
                        'billing_email'     =>  $data['payer_email'],
                        'billing_address'   =>  $data['address_street'],
                        'billing_address1'  =>  $data['address_street'],
                        'billing_country'   =>  $data['address_country'],
                        'billing_city'      =>  $data['address_city'],
                        'billing_state'     =>  $data['address_state'],
                        'billing_zip'       =>  $data['address_zip'],
                        'date'              =>  date('Y-n-d G-i-s')
                    );
                    $this->_model->insertShoppingPayPalPayment($dataPayment);
                }
            }
        }
    }

    public function handlerpaypalcreditcardAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

        if ($this->getRequest()->isPost()) {
            $data =  $this->getRequest()->getParams();
            
            $dataForPayment = array(
                'PAYMENTACTION'     =>  'Sale',
                'IPADDRESS'         =>  $_SERVER['REMOTE_ADDR'],
                'CREDITCARDTYPE'    =>  $data['type'],
                'ACCT'              =>  trim($data['cardnumber']),
                'EXPDATE'           =>  str_pad($data['expiration_date_month'], 2, '0', STR_PAD_LEFT).$data['expiration_date_year'],
                'CVV2'              =>  trim($data['verification_number']),
                'FIRSTNAME'         =>  trim($data['firstname']),
                'LASTNAME'          =>  trim($data['lastname']),
                'STREET'            =>  trim($data['billing_address1']),
                'STREET2'           =>  trim($data['billing_address2']),
                'CITY'              =>  trim($data['city']),
                'STATE'             =>  $data['state'],
                'COUNTRYCODE'       =>  $data['country'],
                'ZIP'               =>  trim($data['zip']),
                'PHONENUM'          =>  trim($data['phone']),
                'AMT'               =>  $data['amt'],
                'CURRENCYCODE'      =>  $data['currency_code'],
                'DESC'              =>  $data['desc']
            );
            
            if ($data['tax'] !== '' && $data['tax'] !== '0.00') {
                $dataForPayment['TAXAMT'] = $data['tax'];
            }
            
            $objPayPal = new RCMS_Object_PayPal_PayPal();
            $payment = $objPayPal->createDoDirectPayment($dataForPayment);
            
            if (preg_match('/success/i', $payment['ACK']) && isset($payment['TRANSACTIONID'])) {
                $infoPayment = $objPayPal->getTransactionDetails($payment['TRANSACTIONID']);
                
                if (preg_match('/success/i', $infoPayment['ACK'])) {
                    $dataPayment = array(
                        'transaction_id'    =>  $infoPayment['TRANSACTIONID'],
                        'amount'            =>  $infoPayment['AMT'],
                        'payer_id'          =>  $infoPayment['PAYERID'],
                        'description'       =>  $data['desc'],
                        'billing_name'      =>  trim($data['firstname']).' '.trim($data['lastname']),
                        'billing_email'     =>  (isset($infoPayment['EMAIL'])?$infoPayment['EMAIL']:''),
                        'billing_address'   =>  trim($data['billing_address1']),
                        'billing_address1'  =>  trim($data['billing_address2']),
                        'billing_country'   =>  $data['country'],
                        'billing_city'      =>  trim($data['city']),
                        'billing_state'     =>  $data['state'],
                        'billing_zip'       =>  trim($data['zip']),
                        'date'              =>  date('Y-n-d G-i-s')
                    );
                    $this->_model->insertShoppingPayPalPayment($dataPayment);
                    echo json_encode(array('done' => true)); return;
                }
                echo json_encode(array('done' => false)); return;
            }
            echo json_encode(array('done' => false)); return;
        }
    }
}
